import React, {
  MouseEventHandler,
  ReactPropTypes,
  Ref,
  useEffect,
  useRef,
  useState,
} from 'react';
import { createPortal } from 'react-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCoffee } from '@fortawesome/free-solid-svg-icons';
import { motion } from 'framer-motion';

interface Props {
  projectName: string;
  onClick: MouseEventHandler<HTMLDivElement>;
  updateTime: string;
}

const ContextMenu = React.forwardRef<HTMLDivElement, { x: number; y: number }>(
  (props, ref) => {
    return createPortal(
      <div
        className="context-menu"
        style={{
          top: Math.min(window.innerHeight - 200, props.y),
          left: Math.min(window.innerWidth - 50, props.x),
        }}
        ref={ref}
      >
        <div className="context-menu-item">编辑</div>
        <div className="context-menu-item">删除</div>
      </div>,
      document.getElementById('context-menu') as HTMLDivElement
    );
  }
);

function History(props: Props) {
  const { projectName = 'Donkey', onClick = () => {}, updateTime } = props;
  const [menuShow, setMenuShow] = useState(false);
  const [menuPos, setMenuPos] = useState({ x: 100, y: 100 });
  const menuRef = useRef<HTMLDivElement>(null);
  const cardRef = useRef<HTMLDivElement>(null);
  const onMouseDownListener = (e: MouseEvent) => {
    if (!menuRef.current) return;
    if (!e.target) return;
    console.log('mouse', e);
    console.log('menu ref', menuRef.current);
    console.log('card ref', cardRef);
    if (!menuRef.current.contains(e.target as HTMLDivElement)) {
      setMenuShow(false);
    }
  };
  useEffect(() => {
    window.addEventListener('mousedown', onMouseDownListener, true);
  }, []);
  return (
    <motion.a whileHover={{ scale: 1.1 }}>
      <div
        ref={cardRef}
        className="history"
        onContextMenu={(e) => {
          e.preventDefault();
          setMenuShow(true);
          setMenuPos({ x: e.clientX, y: e.clientY });
        }}
        onClick={onClick}
      >
        <FontAwesomeIcon
          style={{ width: '5rem', height: '2rem' }}
          icon={faCoffee}
        />
        <ul className="history-details">
          <li>
            项目名称:<span className="data">{projectName}</span>
          </li>
          <li>
            项目状态：
            <span className={'data status'.concat(updateTime ? '' : ' bad')}>
              {updateTime ? '已匿名' : '未匿名'}
            </span>
          </li>
          <li>
            属性数量:
            <span className="data">--</span>
          </li>
          <li>
            最后修改时间:
            <span className="data">
              {updateTime ? new Date(updateTime).toLocaleString() : '--'}
            </span>
          </li>
        </ul>
      </div>
      {menuShow && <ContextMenu ref={menuRef} x={menuPos.x} y={menuPos.y} />}
    </motion.a>
  );
}

export default History;
